/*
批量较正文件名
*/

const fs = require("fs");
const path = require('path');

const getFileName = fileName => {
	const lastIdx = fileName.lastIndexOf('.');
	return {
		name:fileName.substr(0,lastIdx),
		type:fileName.substr(lastIdx+1),
	}
}

const addZero = (num,places=3) => {
	// places = 3;//数字位数，用于补0
	let str = String(num);
	const len = places - str.length;
	if(len > 0){
		for(let i=0;i<len ;i++){
			str = '0' + str;
		}
	}
	// console.log('in addZero',num,'-->',str)
	return str;
}

const createNewName = name => {
	// 根据不同的规则写不同的命名逻辑
	name = name.substr(name.indexOf('第'));//去掉 第 前多余字符
	const search = name.match(/第(\d+)章/);
	if(search){
		const num = parseInt(search[1],10);
		name = name.replace(search[0],`第${addZero(num)}章`);
		name = name.replace('...','');
	}
	return name;
}

const getFolderFiles = (_path) => {

	// 同步读取上级目录下的所有文件到files中
	const files = fs.readdirSync(_path);
	for(let i=0,file,len=files.length;i<len;i++){
		const fileName = files[i];

		const oName = getFileName(fileName);
		const newName = createNewName(oName.name);
		const url = _path;
		const newUrl = path.join(url,[newName,oName.type].join('.'));
		const oldUrl = path.join(url,fileName);

		console.log(oldUrl,newUrl)
		let hasError = false;
		fs.rename(oldUrl, newUrl, (err) => {
            if(err){
            	console.log('completed --->',err)
            	hasError = true;
            }
        });
        // if(i > 0) break;
        if(hasError) break;
	}
}

// console.log(addZero(2))
// console.log(createNewName('107、第10章.txt'))
getFolderFiles(path.join(__dirname,'/江湖夜雨十年灯1'));
